package xiao_jin.fantastic_journey.core.common.block.entity.relictechblock;

import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.inventory.SimpleInventory;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtList;
import net.minecraft.network.listener.ClientPlayPacketListener;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket;
import net.minecraft.registry.RegistryWrapper;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.math.BlockPos;
import org.jetbrains.annotations.NotNull;
import xiao_jin.fantastic_journey.core.init.ModBlockEntity;


public class RelictechTableBlockEntity extends BlockEntity {
    public SimpleInventory inventory = new SimpleInventory(1) {
        @Override
        public int getMaxCountPerStack() {
            return 1;
        }
    };

    public RelictechTableBlockEntity(BlockPos pos, BlockState state) {
        super(ModBlockEntity.RELICTECH_TABLE_BLOCK_ENTITY, pos, state);
    }

    @Override
    public void readNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) {
        super.readNbt(nbt, registryLookup);
        inventory.readNbtList((NbtList) nbt.get("inventory"), registryLookup);
    }

    @Override
    public void writeNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) {
        nbt.put("inventory", inventory.toNbtList(registryLookup));
        super.writeNbt(nbt, registryLookup);
    }

    @Override
    public Packet<ClientPlayPacketListener> toUpdatePacket() {
        return BlockEntityUpdateS2CPacket.create(this);
    }

    @Override
    public void markDirty() {
        super.markDirty();
        var world = this.getWorld();
        assert world != null;
        if (world.isClient) return;
        world.getPlayers().forEach(it -> ((ServerPlayerEntity) it).networkHandler.sendPacket(this.toUpdatePacket()));
    }

    @Override
    public @NotNull NbtCompound toInitialChunkDataNbt(RegistryWrapper.WrapperLookup registryLookup) {
        var tag = super.toInitialChunkDataNbt(registryLookup);
        this.writeNbt(tag, registryLookup);
        return tag;
    }
}